package com.aliwo.constant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:xuyayuan
 * @date:2021/7/27 17:12
 * @description: 运行任务的时候进行sql规则匹配
 */
public class IllegalSqlUtil {
    private static final Logger logger = LoggerFactory.getLogger(IllegalSqlUtil.class);
    // 正则匹配不合规sql
    public static final String regAll = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
            + "(\\b(update|and|or|join|on|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master" +
            "|into|drop|execute)\\b)";

    static Pattern sqlPattern = Pattern.compile(regAll, Pattern.CASE_INSENSITIVE);//表示忽略大小写

    /***************************************************************************
     * 参数校验
     *
     * @param str ep: "or 1=1"
     */
    public static boolean isSqlValid(String str) {
        Matcher matcher = sqlPattern.matcher(str);
        if (matcher.find()) {
            System.out.println("参数存在非法字符，请确认："+matcher.group());//获取非法字符：or
            return false;
        }
        return true;
    }

    public static String getIllegalSqlInfo(String str) {
        Matcher matcher = sqlPattern.matcher(str);
        if (matcher.find()) {
            System.out.println("参数存在非法字符，请确认："+matcher.group());//获取非法字符：or
            return matcher.group();
        }
        return null;
    }

    /**
     * 功能描述:返回不合规所有的字符
     *
     * @param str
     * @return java.lang.String
     * @author xuyayuan
     */
    public static String getAllIllegalSqlInfo(String str) {
        Matcher matcher = sqlPattern.matcher(str);
        Set<String> set = new HashSet<>();
        while (matcher.find()) {
            set.add(matcher.group());
        }
        return (set != null && set.size() > 0) ? set.toString() : null;
    }

}
